package com.qili.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author liuyang
 * @date 2021/1/30
 * @description     图片工具类
 */
public class ImageUtil {


    /*
     * @Date 11:46 2021/1/30
     * @Description 图片背景设置为透明方法
     * @Param sourceFilePath 源图片文件路径
     * @Param targetFilePath 生成透明文件路径
     */
    public static void transparentBackground(String sourceFilePath,String imgNameFormat,String targetFilePath) throws IOException {
        BufferedImage temp = ImageIO.read(new File(sourceFilePath));
        //取得图片的长和宽
        int imgHeight = temp.getHeight();
        int imgWidth = temp.getWidth();
        //新建一个类型支持透明的BufferedImage
        BufferedImage bi = new BufferedImage(imgWidth, imgHeight,BufferedImage.TYPE_4BYTE_ABGR);
        for(int i = 0; i < imgWidth; ++i){
            for(int j = 0; j < imgHeight; ++j){
                int tempRgb = temp.getRGB(i,j);
                int r = (tempRgb & 16711680) >> 16;
                int g = (tempRgb & 65280) >> 8;
                int b = (tempRgb & 255);
                Boolean ss=true;
                //白色接近的设置为透明,否则为源文件
                if(((255 - r) < 130) && ((255 - g) < 130) && ((255 - b) < 130)){
                    bi.setRGB(i, j, -1 & 0x00ffffff);
                    ss=false;
                }else if(r > 120  && g<150 && b< 150  && ss){
                    int rgb = temp.getRGB(i, j);
                    Color color = new Color(rgb);
                    int red = r+80;
                    int green=g;
                    int blue = b;
                    if(red>255) {
                       red=255;
                    }
                    if(green>255) {
                       green=255;
                    }
                   if(blue>255) blue=255;
                   if(blue<0) blue=0;
                    color = new Color(red,green,blue);
                    int rgb1 = color.getRGB();
                    bi.setRGB(i,j,rgb1);
                } else{
                    bi.setRGB(i, j, temp.getRGB(i, j));
                }
            }
        }
        ImageIO.write(bi,imgNameFormat,new File(targetFilePath));
    }

}
